package com.xl6667.job;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xl6667.constants.SystemConstants;
import com.xl6667.domain.entity.Article;
import com.xl6667.enums.AppHttpCodeEnum;
import com.xl6667.exception.SystemException;
import com.xl6667.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
@Slf4j
public class EsScheduled {
    @Autowired
    private ArticleService articleService;

    /**
     * 每隔一个小时更新es
     */
    @Scheduled(cron = "0 0 0/1 * * ? ")
    public void articleEs(){
        log.info("定时更新es");
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200,"http")));
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getDelFlag, SystemConstants.DEL_FLAG_NORMA);

        List<Article> list = articleService.list();
        BulkRequest bulkRequest = new BulkRequest();
        for (Article article : list) {
            IndexRequest indexRequest = new IndexRequest("article").id(article.getId().toString());
            String s = JSON.toJSONString(article);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        try {
            client.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new SystemException(AppHttpCodeEnum.SYSTEM_ERROR);
        }
    }
}
